package cyan.gf.db;

import cyan.gf.control.MessageBox;
import javafx.application.Platform;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by cyan on 2017/1/20.
 * Email:qsyan@vip.qq.com
 */
public class DBHelper {

  private static CrudInstance instance;
  private static Logger logger = LogManager.getLogger(CrudInstance.class);

  public static CrudInstance instance(JdbcProp jdbcProp) {
    if (instance == null) {
      try {
        Class.forName(jdbcProp.getDriverName());
        Connection connection = DriverManager.getConnection(jdbcProp.getUrl(), jdbcProp.getUserName(), jdbcProp.getPassword());
        instance = new CrudInstance(connection, jdbcProp);
      } catch (ClassNotFoundException | SQLException e) {
        logger.error(e);
        Platform.runLater(() -> {
          MessageBox.error("main", e.getMessage());
        });
      }
    }
    return instance;
  }

  public static void close() {
    instance.destroy();
    instance = null;
  }

  public static boolean isClosed() {
    return instance == null;
  }

}
